package de.baumann.browser.activitys.oc

import android.content.Context
import android.content.Intent
import de.baumann.browser.R
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.base.BasePresenter
import de.baumann.browser.iview.IBaseView
import de.baumann.browser.utils.web3j.*
import de.baumann.browser.views.dialog.PayPwdDialog
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_oc_b_transfer.*
import kotlinx.android.synthetic.main.include_tool_bar.*
import java.math.BigDecimal
import java.math.BigInteger

class OCBTransferActivity : BaseOdinActivity<IBaseView, BasePresenter<IBaseView>>() {

    companion object {
        fun startOCBTransferActivity(context: Context, a: String, url: String, ca: String, cn: String) {
            context.startActivity(Intent(context, OCBTransferActivity::class.java).apply {
                putExtra("a", a)
                putExtra("url", url)
                putExtra("ca", ca)
                putExtra("cn", cn)
            })
        }
    }


    override fun getLayout(): Int {
        return R.layout.activity_oc_b_transfer
    }

    override fun getTitleText(): String {
        return "转账"
    }

    private var pwdDialog: PayPwdDialog? = null

    override fun initView() {
        initToolbar(commToolBar, commTitle)
        tcn.text = intent.getStringExtra("cn")
        tvCBalance.text = "可用 0.0000 ${intent.getStringExtra("cn")}"

        tvAllCB.setOnClickListener {
            edCAmount.setText(balance.toString())
        }

        btnCTransfer.setOnClickListener {
            if (getToA().isEmpty()) {
                showShortToast("请输入地址")
                return@setOnClickListener
            }

            if (getV().isEmpty()) {
                showShortToast("请输入数量")
                return@setOnClickListener
            }

            pwdDialog = PayPwdDialog(mContext, object : PayPwdDialog.PwdCallback {
                override fun callback(pwd: String) {
                    transfer(pwd)
                }
            })

            pwdDialog!!.show()
        }
    }

    override fun initData() {
        getBalance()
    }

    private var balance: BigDecimal = BigDecimal(0.0000)
    private fun getBalance() {
        Observable.create(ObservableOnSubscribe<BigDecimal> { emitter ->
            val balance = TokenUtil.getBalance2(intent.getStringExtra("url"),
                    intent.getStringExtra("a"),
                    intent.getStringExtra("ca"))
            if (balance != null) {
                emitter.onNext(balance)
            } else {
                emitter.onError(Throwable("余额获取失败"))
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<BigDecimal> {
                    override fun onComplete() {

                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: BigDecimal) {
                        balance = t
                        tvCBalance.text = "可用 $balance ${intent.getStringExtra("cn")}"
                    }

                    override fun onError(e: Throwable) {
                        view!!.onError(e.message)
                    }
                })
    }


    fun transfer(pwd: String) {
        Observable.create(ObservableOnSubscribe<String> { emitter ->
            try {
                val wallet = WalletDaoUtils.queryWalletByAddress(getA())
                if (wallet == null) {
                    emitter.onError(Throwable("钱包信息加载失败"))
                    return@ObservableOnSubscribe
                }

                val pk = TokenUtil.getPrivateKey(pwd, wallet)
                val hashs = Erc20Util.transferERC20Token(getUrl(), getA(), getToA(), getV(), pk, getCa())
                if (hashs != null) {
                    emitter.onNext(hashs)
                }
            } catch (e: Exception) {
                if ("Invalid password provided" == e.message) {
                    emitter.onError(Throwable("密码错误"))
//                    Toast.makeText(mContext, "密码错误", Toast.LENGTH_SHORT).show()
                } else {
                    emitter.onError(e)
                }
                e.printStackTrace()
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<String> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: String) {
                        pwdDialog?.dismiss()
                        showShortToast("交易已发送")
                        getBalance()
                    }

                    override fun onError(e: Throwable) {
                        showShortToast(e.message)
//                        if (e.message != null) {
//                            view!!.onError(e.message);
//                        }
                    }
                })
    }

    private fun getUrl(): String {
        return intent.getStringExtra("url")
    }

    private fun getA(): String {
        return intent.getStringExtra("a")
    }

    private fun getCa(): String {
        return intent.getStringExtra("ca")
    }

    private fun getToA(): String {
        var toa = edcToAddress.text.toString().trim()
        if (toa.startsWith("odx")){
            toa = "0x${toa.substring(3)}"
        }
        return toa
    }

    private fun getV(): String {
        return edCAmount.text.toString().trim()
    }

    override fun createPresenter(): BasePresenter<IBaseView>? {
        return null
    }

    override fun createView(): IBaseView? {
        return null
    }

}